package com.tuyue.police.handler;

import com.tuyue.police.enums.ResultEnum;
import com.tuyue.police.exception.MyException;
import com.tuyue.police.util.Result;
import com.tuyue.police.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;


/**
 * 统一异常处理
 * Created by Administrator on 2017/5/25.
 */
@ControllerAdvice
public class ExceptionHandle {
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e){
        logger.info(e.toString());
        if (e instanceof MyException){
            MyException myException= (MyException) e;
            return ResultUtil.error(myException.getCode(),myException.getMessage());
        }else if(e instanceof NullPointerException){
            return ResultUtil.error(500,e.toString());
        }else if(e instanceof HttpRequestMethodNotSupportedException){
            return ResultUtil.error(405,"请求方式异常");
        }else if(e instanceof BindException){
            //自定义注解异常处理
            StringBuffer sb = new StringBuffer();
            for (FieldError fieldError : ((BindException) e).getBindingResult().getFieldErrors()) {
                sb.append("  ");
                sb.append(fieldError.getDefaultMessage());
            }
            return ResultUtil.error(400,sb.toString());
        }else if(e instanceof MethodArgumentTypeMismatchException){
            return ResultUtil.error(400,e.toString());
        }else if(e instanceof MissingServletRequestParameterException){
            return ResultUtil.error(400,e.getMessage());
        }else if (e instanceof HttpMessageNotReadableException){
            return ResultUtil.error(400,"传输参数类型和接收类型不匹配");
        }else if (e instanceof DataIntegrityViolationException){
            return ResultUtil.error(300,"数据库字段不能为空");
        }else{
            logger.info("【系统异常】 {}",e.getMessage());
            return ResultUtil.error(ResultEnum.UNKONW_ERROR);
        }
    }

}
